package com.carworld.controller;

import com.jfinal.aop.Before;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.tx.Tx;

import java.io.UnsupportedEncodingException;
import com.alibaba.fastjson.JSONObject;
import com.carworld.config.BaseController;
import com.carworld.model.SysUser;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.api.SnsApi;
import com.jfinal.weixin.sdk.api.SnsAccessToken;

public class IndexController extends BaseController {

	private static String appId = PropKit.get("appIdUser");
	private static String appSecret = PropKit.get("appSecretUser");

	public void index() {
		redirect("/carworld");
	}

	/**
	 * 获取用户信息CODE isBase为false,snsapi_userinfo（弹出授权页面，通过 openid拿到用户基本信息）
	 * 
	 * @throws UnsupportedEncodingException
	 */
	public void getCode() throws UnsupportedEncodingException {
		String queryState = getQueryState();
		boolean isBase = getParaToBoolean("isBase", false);
		System.out.println("appid:" + appId + ", appSecret=" + appSecret);
		//String redirectUri = java.net.URLEncoder.encode(getCtx() + "/getBaseUserInfo", "UTF-8");
		//nginx 转发以后变成了127.0.0.1 微信不通过，所以hardcode 域名
		String redirectUri = java.net.URLEncoder.encode( "http://food.3kkk.xyz/carworld_weixin/getBaseUserInfo", "UTF-8");
		redirect(SnsAccessTokenApi.getAuthorizeURL(appId, redirectUri, queryState, isBase));
	}

	// 获取微信用户信息
	public void getBaseUserInfo() {
		String state = getPara("state");
		String code = getPara("code");
		String url = "/carworld";
		if (StrKit.isBlank(code)) {
			redirect(url);
			return;
		}
		// 根据code,appId,appSecret获取用户accessToken,并存入缓存
		SnsAccessToken st = SnsAccessTokenApi.getSnsAccessToken(appId, appSecret, code);
		// st.getAccessToken(); 此为网页授权接口调用凭证,与基础支持的access_token不同
		String openId = st.getOpenid();
		System.out.println("customer openId: " + openId);
		JSONObject userInfo = JSONObject.parseObject(SnsApi.getUserInfo(st.getAccessToken(), st.getOpenid()).getJson());
		System.out.println("userInfo: " + userInfo.toString());
		SysUser.dao.save(userInfo, this);  
		if (StrKit.notBlank(state)) {
			if (state.indexOf("shareBy") > -1) { // 会员绑定,进入UserController中bindMember方法
				url = "/user/bindMember?" + parsingQueryState(state);
			} else if (state.indexOf("shopId") > -1) { // 顾客点单
				url = "/order/customerOrder?" + parsingQueryState(state);
			} else if (state.indexOf("couponMealId") > -1) { // 用户领取套餐
				url = "/vipcard/receivedCoupon?" + parsingQueryState(state);
			} else if(state.indexOf("shareCard") > -1){
				url = "/vipcard/receivedVipCard?" + parsingQueryState(state);
			} else {
				url = "/carworld";
			}
		}
		System.out.println("获取用户信息后的URL:" + url);
		redirect(url);
		return;

	}

}
